﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using PMS.Win;
using DevExpress.XtraBars;
using PMS.Resources;
using PMS.Utils;
using PMS.BLL;
using PMS;
using PMS.Entity;
using DevExpress.XtraNavBar;
using DevExpress.XtraNavBar.ViewInfo;
using System.Drawing.Drawing2D;
using PMS.DanhMucChung;
using PMS.ChucNang;
using PMS.SYS;

namespace PMS
{

    public partial class Main : BaseForm
    {
        #region Const
        private const string EXIT_APP_CONFIRM = "EXIT_APP_CONFIRM";
        private const string GEN_CONFIRM = "GEN_CONFIM";
        #endregion

        #region Declare
        private string m_activeformID = null;
        private List<Form> listForm = null;
        private static List<NavBarGroup> root = new List<NavBarGroup>();
        private bool isCustomDraw = false;
        #endregion

        #region Contructor
        public Main()
        {
            InitializeComponent();
            LoadMenuLanguage();
            Init();
            UpdateToolBarButtonStatus(null);
            LoadMenuPermisstionAccessable();

        }

        public void Init()
        {
            this.bsiUsername.Caption = CurrentUser.Hoten;
            this.bsiToDay.Caption = DateTime.Now.ToShortDateString();
        }
        #endregion

        #region methods

        private void AddOpeningFormToMenuList(BaseForm OpeningForm)
        {
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Main));
            DevExpress.XtraBars.BarButtonItem item = new BarButtonItem();
            item.Name = OpeningForm.functionID;
            item.Caption = OpeningForm.Text;
            item.Glyph = ((System.Drawing.Image)(resources.GetObject("bmnOpeningFormList.Glyph")));
            this.bmnOpeningFormList.AddItem(item);
            this.Update();
        }

        private void RemoveOpeningFormFromMenuList(BaseForm form)
        {
            int posItem = -1;
            for (int i = 0; i < barManager1.Items.Count; i++)
            {
                if (barManager1.Items[i].Caption == form.Text)
                {
                    posItem = i;
                }
            }
            if (posItem > 0)
            {
                barManager1.Items.RemoveAt(posItem);
            }
        }

        private void LoadMenuPermisstionAccessable()
        {
            if (CurrentUser == null)
            {
                for (int i = 0; i < barManager1.Items.Count; i++)
                {

                    if (barManager1.Items[i] is BarButtonItem)
                    {
                        barManager1.Items[i].Enabled = false;
                    }
                }
                this.SYS_LogOut.Enabled = false;
                this.SYS_Login.Enabled = true;
            }
            else
            {
                for (int i = 0; i < barManager1.Items.Count; i++)
                {

                    if (barManager1.Items[i] is BarButtonItem)
                    {
                        barManager1.Items[i].Enabled = true;
                    }
                }
                this.SYS_LogOut.Enabled = true;
                this.SYS_Login.Enabled = false;
                if (CurrentUser.Role == (int)AccountRole.Admin)
                {
                    SYS_Account.Enabled = true;
                }
                else
                {
                    SYS_Account.Enabled = false;
                }
            }

            //All users can use
            this.SYS_CloseOpeningForm.Enabled = true;
            this.SYS_CloseAllForm.Enabled = true;
            this.SYS_Exit.Enabled = true;
            this.HEL_Tourial.Enabled = true;
            this.HEL_About.Enabled = true;
        }

        private void LoadMenuLanguage()
        {
            
            for (int i = 0; i < barManager1.Items.Count; i++)
            {
                if(barManager1.Items[i].Name.Equals("bmnOpeningFormList"))
                {
                    barManager1.Items[i].Caption = "";
                }
                string caption = FormResources.GetString(this.Name + "." + barManager1.Items[i].Name);
                if(!string.IsNullOrEmpty(caption))
                {
                    barManager1.Items[i].Caption = caption;
                }

            }
        }

        private void Login()
        {

            using (LoginForm f = new LoginForm())
            {
                if (f.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    if (IsLoggedIn)
                    {
                        CloseOpenedForms();
                        LoadMenuLanguage();
                        this.bsiUsername.Caption = CurrentUser.Hoten;
                        LoadMenuPermisstionAccessable();
                    }
                }
            }

        }

        private void LogOut()
        {
            IsLoggedIn = false;
            CurrentUser = null;
            CloseOpenedForms();
            this.bsiUsername.Caption = "";
            LoadMenuPermisstionAccessable();
            this.Update();
            this.Login();
        }

        private void changePassWord()
        {
            using (ChangePassword form = new ChangePassword(CurrentUser) { StartPosition = FormStartPosition.CenterScreen })
            {
                form.ShowDialog();
            }
        }

        private void CloseActivingForm()
        {
            var form = this.ActiveMdiChild as BaseForm;
            if(form!=null) form.Close();
        }


        private void menuItem_LinkClicked(object sender, NavBarLinkEventArgs e)
        {
            NavBarItem navBarItem = sender as NavBarItem;
            if (navBarItem != null)
            {
                DoActionMenuItemClick(navBarItem.Name.ToString());
            }
        }

        private void DoActionMenuItemClick(string name)
        {
            switch (name)
            {

                //MDM  SD_Sales 
                case "MDM_Customers": AddForm(typeof(CustomerEntry), name); break;
                case "MDM_Unit": AddForm(typeof(UnitEntry), name); break;
                case "MDM_Vendor": AddForm(typeof(VendorEntry), name); break;
                case "MDM_Inventory": AddForm(typeof(InventoryEntry), name); break;
                case "MDM_Category": AddForm(typeof(CategoryEntry), name); break;
                case "MDM_Product": AddForm(typeof(ProductEntry), name); break;
                case "MDM_Companies": AddForm(typeof(CongTyEntry), name); break;

                // Chuc Nang CN_DongMoKy
                case "CN_NhapKho": AddForm(typeof(NhapKhoEntry), name); break;
                case "CN_XuatKho": AddForm(typeof(XuatKhoEntry), name); break;
                case "CN_GiaoHang": AddForm(typeof(GiaoHangEntry), name); break;
                //case "CN_BienBanKiemKeKho": AddForm(typeof(BienBanKiemKeKhoEntry), name); break;
                case "CN_BienBanKiemKeKho": AddForm(typeof(BienBanKiemKeKhoEntry2), name); break;
                case "CN_ThanhToan": AddForm(typeof(ThanhToanEntry), name); break;
                case "CN_BienBanNhapKho": AddForm(typeof(BienBanNhapKhoEntry), name); break;
                case "CN_CongNoCuaKhachHang": AddForm(typeof(CongNoDenHanCuaKhachHang), name); break;
                case "CN_DanhSachThuocHetHan": AddForm(typeof(ThongBaoThuocHetHan), name); break;
                case "CN_DongMoKy": AddForm(typeof(DongMoKyForm), name); break;

                //SYS SYS_CloseAllForm
                case "SYS_Account": AddForm(typeof(AccountEntry), name); break;
                case "SYS_CloseOpeningForm": CloseActivingForm(); break;
                case "SYS_CloseAllForm": CloseOpenedForms(); break;
                case "SYS_Login": Login(); break;
                case "SYS_LogOut": LogOut(); break;
                case "SYS_UserChangePass": changePassWord(); break;
                case "SYS_Backup": AddForm(typeof(BackupAndRestore), name); break;
                case "SYS_Exit": this.Close(); break;
                //Report RP_BaoCaoXuatNhapTon
                //case "RP_TheKho": AddForm(typeof(TheKhoForm), name); break;
                case "RP_TheKho": AddForm(typeof(TheKhoByDate), name); break;
                case "RP_CacSPKHDaMua": AddForm(typeof(BaoCaoSanPhamKhachHangDaMuaForm), name); break;
                case "RP_KhachHangDaMuaSP": AddForm(typeof(BaoCaoKhachHangDaMuaSanPhamForm), name); break;
                case "RP_DoanhThuCuaSP": AddForm(typeof(DoanhThuCuaSanPhamForm), name); break;
                case "RP_CongNoChiTietCuaKhachHang": AddForm(typeof(BaoCaoCongNoCuaKhachHangForm), name); break;
                case "RP_ChiTietNhapXuatSanPham": AddForm(typeof(ChiTietNhapXuatSanPham), name); break;
                case "RP_BaoCaoXuatNhapTon": AddForm(typeof(BaoCaoXuatNhapTonForm), name); break;
                //Help 
                case "HEL_Tourial":
                    System.Diagnostics.Process.Start(Application.StartupPath + "\\User manual.pdf"); 
                    break;


            }
        }

        private void CloseOpenedForms()
        {
            foreach (var item in this.MdiChildren)
            {
                item.Close();
            }
        }

        private void Main_PropertyChanged(object sender, EventArgs e)
        {
            if (sender is FormEntryBase)
            {
                var f = (FormEntryBase)sender;
                m_activeformID = null;
                if ((e as PropertyChangedEventArgs).PropertyName == "ShowPopup")
                {
                    m_activeformID = (f as FormEntryBase).functionID;
                }
                else
                {
                    this.UpdateToolBarButtonStatus(f);
                }
            }
        }

        private void UpdateToolBarButtonStatus(FormEntryBase formAdd)
        {
            if (formAdd == null)
            {
                this.btNew.Enabled = false;
                this.btCancel.Enabled = false;
                this.btDelete.Enabled = false;
                this.btSave.Enabled = false;
                this.btFinish.Enabled = false;
                this.btPrint.Enabled = false;
            }else
            {
                this.btNew.Enabled = formAdd.CanNew;
                this.btCancel.Enabled = formAdd.CanCancel;
                this.btDelete.Enabled = formAdd.CanDelete;
                this.btSave.Enabled = formAdd.CanSave;
                this.btFinish.Enabled = formAdd.CanFinish;
                this.btPrint.Enabled = formAdd.CanPrint;
            }
        }

        public void AddForm(Type formType, string functionID)
        {
            this.AddForm(formType, false, functionID);
        }

        private void AddForm(Type formType, bool isShowDialog, string functionID)
        {
            if (this.listForm == null)
            {
                this.listForm = new List<Form>();
            }

            if (this.listForm.Exists(f => f.GetType() == formType))
            {
                Form currentForm = listForm.Find(f => f.GetType() == formType);
                currentForm.WindowState = FormWindowState.Normal;
                currentForm.Activate();
                return;
            }

            BaseForm form;
            // Functions which are need no check permission must be inherited from FormPopupBase
            if (formType.BaseType.Equals(typeof(FormPopupBase)))
            {
                form = (BaseForm)Activator.CreateInstance(formType);
            }
            else
            {
                form = (BaseForm)Activator.CreateInstance(formType, new object[] { functionID });
            }

            this.listForm.Add(form);

            form.Activated += (sender, e) =>
            {
                if (sender is FormEntryBase)
                {

                    foreach (LinkPersistInfo item in this.toolBar.LinksPersistInfo)
                        item.Item.Enabled = true;

                    var f = (FormEntryBase)sender;
                    f.PropertyChanged += Main_PropertyChanged;

                    this.UpdateToolBarButtonStatus(f);
                }
            };

            form.Deactivate += (sender, e) =>
            {
                if (sender is FormEntryBase)
                {
                    ((FormEntryBase)sender).PropertyChanged -= Main_PropertyChanged;
                    foreach (LinkPersistInfo item in this.toolBar.LinksPersistInfo)
                        item.Item.Enabled = false;
                }
            };

            form.FormClosed += (sender, e) =>
            {
                RemoveOpeningFormFromMenuList(form);
                this.listForm.Remove(form);
                
                form.ForceToValidate = false;
                if (this.listForm.Count == 0)
                {
                    foreach (LinkPersistInfo item in this.toolBar.LinksPersistInfo)
                        item.Item.Enabled = false;
                }
            };
            if (!form.ForceClose)
            {
                if (isShowDialog)
                {
                    form.ShowDialog();
                }
                else
                {
                    form.TopLevel = false;
                    form.MdiParent = this;
                    form.Activate();
                    form.StartPosition = FormStartPosition.CenterScreen;
                    form.Show();
                    AddOpeningFormToMenuList(form);
                    //string title = GetFormTitle(functionID);
                    //if (!string.IsNullOrEmpty(title))
                    //{
                    //    form.Text = title;
                    //}
                }
            }
        }

        #endregion

        #region Events

        private void Main_FormClosing(object sender, FormClosingEventArgs e)
        {
            bool isNeedConfirm = false;
            foreach (Form form in this.MdiChildren)
            {
                if(form.GetType().Equals(typeof(FormEntryBase)))
                {
                    if (!((FormEntryBase)form).IsNew)
                    {
                        isNeedConfirm = true;
                    }
                }
            }

            if (isNeedConfirm)
            {
                DialogResult rs = MessageBox.Show(Messages.GetString(EXIT_APP_CONFIRM), FormResources.GetString(GEN_CONFIRM), MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (rs == DialogResult.No)
                {
                    e.Cancel = true;
                }
            }
        }

        private void barManager1_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (e.Item.Name.Contains("bt"))
            {
                if (this.ActiveMdiChild is FormEntryBase)
                {
                    var form = this.ActiveMdiChild as FormEntryBase;

                    if (e.Item == btNew)
                        form.DoNew();
                    else if (e.Item == btSave)
                        form.DoSave();
                    else if (e.Item == btCancel)
                        form.DoCancel();
                    else if (e.Item == btDelete)
                        form.DoDelete();
                    else if (e.Item == btFinish)
                        form.DoFinish();
                    else if (e.Item == btPrint)
                        form.DoPrint();
                   
                }

            }
            else
            {
                DoActionMenuItemClick(e.Item.Name);
            }
        }

        #endregion

        private void navBarControl1_MouseUp(object sender, MouseEventArgs e)
        {
            NavBarHitInfo hInfo = ((NavBarControl)sender).CalcHitInfo(e.Location);
            if (hInfo.InGroupCaption)
                hInfo.Group.Expanded = !hInfo.Group.Expanded;
        }

        private void dockPanel1_ClosingPanel(object sender, DevExpress.XtraBars.Docking.DockPanelCancelEventArgs e)
        {
            e.Cancel = true;
        }

        private void Main_Load(object sender, EventArgs e)
        {
            foreach (Control control in this.Controls)
            {
                if (control is MdiClient) // located it
                {
                    try
                    {
                        control.BackgroundImageLayout = ImageLayout.Stretch;
                        control.BackgroundImage = Image.FromFile(Constants.MDI_LOGO_FILE_NAME);   
                        break;
                    }
                    catch { }
                }
            }

        }

    }
}
